[[...path]].page.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  1. import type { ReactNode } from 'react';
  2. import React, { useEffect } from 'react';
  3. import EventEmitter from 'events';
  4. import { isIPageInfoForEntity } from '@growi/core';
  5. import type {
  6. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision,
  7. } from '@growi/core';
  8. import {
  9. isClient, pagePathUtils, pathUtils,
  10. } from '@growi/core/dist/utils';
  11. import ExtensibleCustomError from 'extensible-custom-error';
  12. import type {
  13. GetServerSideProps, GetServerSidePropsContext,
  14. } from 'next';
  15. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  16. import dynamic from 'next/dynamic';
  17. import Head from 'next/head';
  18. import { useRouter } from 'next/router';
  19. import superjson from 'superjson';
  20. import { BasicLayout } from '~/components-universal/Layout/BasicLayout';
  21. import { PageView } from '~/components-universal/PageView/PageView';
  22. import { DrawioViewerScript } from '~/components-universal/Script/DrawioViewerScript';
  23. import { SupportedAction, type SupportedActionType } from '~/interfaces/activity';
  24. import type { CrowiRequest } from '~/interfaces/crowi-request';
  25. import type { RendererConfig } from '~/interfaces/services/renderer';
  26. import type { ISidebarConfig } from '~/interfaces/sidebar-config';
  27. import type { CurrentPageYjsData } from '~/interfaces/yjs';
  28. import type { PageModel, PageDocument } from '~/server/models/page';
  29. import type { PageRedirectModel } from '~/server/models/page-redirect';
  30. import { useEditorModeClassName } from '~/services/layout/use-editor-mode-class-name';
  31. import {
  32. useCurrentUser,
  33. useIsForbidden, useIsSharedUser,
  34. useIsEnabledStaleNotification, useIsIdenticalPath,
  35. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  36. useDefaultIndentSize, useIsIndentSizeForced,
  37. useIsAclEnabled, useIsSearchPage, useIsEnabledAttachTitleHeader,
  38. useCsrfToken, useIsSearchScopeChildrenAsDefault, useIsEnabledMarp, useCurrentPathname,
  39. useIsSlackConfigured, useRendererConfig, useGrowiCloudUri,
  40. useIsAllReplyShown, useIsContainerFluid, useIsNotCreatable,
  41. useIsUploadAllFileAllowed, useIsUploadEnabled,
  42. } from '~/stores-universal/context';
  43. import { useEditingMarkdown } from '~/stores/editor';
  44. import {
  45. useSWRxCurrentPage, useSWRMUTxCurrentPage, useCurrentPageId,
  46. useIsNotFound, useIsLatestRevision, useTemplateTagData, useTemplateBodyData,
  47. } from '~/stores/page';
  48. import { useRedirectFrom } from '~/stores/page-redirect';
  49. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  50. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  51. import { useCurrentPageYjsData, useSWRMUTxCurrentPageYjsData } from '~/stores/yjs';
  52. import loggerFactory from '~/utils/logger';
  53. import type { NextPageWithLayout } from './_app.page';
  54. import type { CommonProps } from './utils/commons';
  55. import {
  56. getNextI18NextConfig, getServerSideCommonProps, generateCustomTitleForPage, useInitSidebarConfig, skipSSR, addActivity,
  57. } from './utils/commons';
  58. declare global {
  59. // eslint-disable-next-line vars-on-top, no-var
  60. var globalEmitter: EventEmitter;
  61. }
  62. const GrowiContextualSubNavigationSubstance = dynamic(() => import('~/components/Navbar/GrowiContextualSubNavigation'), { ssr: false });
  63. const GrowiPluginsActivator = dynamic(() => import('~/features/growi-plugin/client/components').then(mod => mod.GrowiPluginsActivator), { ssr: false });
  64. const DisplaySwitcher = dynamic(() => import('../components/Page/DisplaySwitcher').then(mod => mod.DisplaySwitcher), { ssr: false });
  65. const PageStatusAlert = dynamic(() => import('../components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  66. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  67. const DescendantsPageListModal = dynamic(() => import('../components/DescendantsPageListModal').then(mod => mod.DescendantsPageListModal), { ssr: false });
  68. const DrawioModal = dynamic(() => import('../components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  69. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  70. const TemplateModal = dynamic(() => import('../components/TemplateModal').then(mod => mod.TemplateModal), { ssr: false });
  71. const LinkEditModal = dynamic(() => import('../components/PageEditor/LinkEditModal').then(mod => mod.LinkEditModal), { ssr: false });
  72. const TagEditModal = dynamic(() => import('../components/PageTags/TagEditModal').then(mod => mod.TagEditModal), { ssr: false });
  73. const ConflictDiffModal = dynamic(() => import('../components/PageEditor/ConflictDiffModal').then(mod => mod.ConflictDiffModal), { ssr: false });
  74. const QuestionnaireModalManager = dynamic(() => import('~/features/questionnaire/client/components/QuestionnaireModalManager'), { ssr: false });
  75. const EditablePageEffects = dynamic(() => import('../components/Page/EditablePageEffects').then(mod => mod.EditablePageEffects), { ssr: false });
  76. const logger = loggerFactory('growi:pages:all');
  77. const {
  78. isPermalink: _isPermalink, isCreatablePage,
  79. } = pagePathUtils;
  80. const { removeHeadingSlash } = pathUtils;
  81. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  82. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  83. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  84. {
  85. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  86. return v?.data != null
  87. && v?.data.toObject != null
  88. && v?.meta != null
  89. && isIPageInfoForEntity(v.meta);
  90. },
  91. serialize: (v) => {
  92. return {
  93. data: superjson.stringify(v.data.toObject()),
  94. meta: superjson.stringify(v.meta),
  95. };
  96. },
  97. deserialize: (v) => {
  98. return {
  99. data: superjson.parse(v.data),
  100. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  101. };
  102. },
  103. },
  104. 'IPageToShowRevisionWithMetaTransformer',
  105. );
  106. // GrowiContextualSubNavigation for NOT shared page
  107. type GrowiContextualSubNavigationProps = {
  108. isLinkSharingDisabled: boolean,
  109. }
  110. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  111. const { isLinkSharingDisabled } = props;
  112. const { data: currentPage } = useSWRxCurrentPage();
  113. return (
  114. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled} />
  115. );
  116. };
  117. type Props = CommonProps & {
  118. pageWithMeta: IPageToShowRevisionWithMeta | null,
  119. // pageUser?: any,
  120. redirectFrom?: string;
  121. // shareLinkId?: string;
  122. isLatestRevision?: boolean,
  123. isIdenticalPathPage?: boolean,
  124. isForbidden: boolean,
  125. isNotFound: boolean,
  126. isNotCreatable: boolean,
  127. // isAbleToDeleteCompletely: boolean,
  128. templateTagData?: string[],
  129. templateBodyData?: string,
  130. isSearchServiceConfigured: boolean,
  131. isSearchServiceReachable: boolean,
  132. isSearchScopeChildrenAsDefault: boolean,
  133. isEnabledMarp: boolean,
  134. sidebarConfig: ISidebarConfig,
  135. isSlackConfigured: boolean,
  136. // isMailerSetup: boolean,
  137. isAclEnabled: boolean,
  138. // hasSlackConfig: boolean,
  139. drawioUri: string | null,
  140. noCdn: string,
  141. // highlightJsStyle: string,
  142. isAllReplyShown: boolean,
  143. isContainerFluid: boolean,
  144. isUploadEnabled: boolean,
  145. isUploadAllFileAllowed: boolean,
  146. isEnabledStaleNotification: boolean,
  147. isEnabledAttachTitleHeader: boolean,
  148. // isEnabledLinebreaks: boolean,
  149. // isEnabledLinebreaksInComments: boolean,
  150. adminPreferredIndentSize: number,
  151. isIndentSizeForced: boolean,
  152. disableLinkSharing: boolean,
  153. skipSSR: boolean,
  154. ssrMaxRevisionBodyLength: number,
  155. yjsData: CurrentPageYjsData,
  156. rendererConfig: RendererConfig,
  157. };
  158. const Page: NextPageWithLayout<Props> = (props: Props) => {
  159. // register global EventEmitter
  160. if (isClient() && window.globalEmitter == null) {
  161. window.globalEmitter = new EventEmitter();
  162. }
  163. const router = useRouter();
  164. useCurrentUser(props.currentUser ?? null);
  165. // commons
  166. useCsrfToken(props.csrfToken);
  167. useGrowiCloudUri(props.growiCloudUri);
  168. // page
  169. useIsContainerFluid(props.isContainerFluid);
  170. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  171. useIsForbidden(props.isForbidden);
  172. useIsNotCreatable(props.isNotCreatable);
  173. useRedirectFrom(props.redirectFrom ?? null);
  174. useIsSharedUser(false); // this page cann't be routed for '/share'
  175. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  176. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  177. useIsSearchPage(false);
  178. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  179. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  180. useIsSearchServiceReachable(props.isSearchServiceReachable);
  181. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  182. useIsSlackConfigured(props.isSlackConfigured);
  183. // useIsMailerSetup(props.isMailerSetup);
  184. useIsAclEnabled(props.isAclEnabled);
  185. // useHasSlackConfig(props.hasSlackConfig);
  186. // useNoCdn(props.noCdn);
  187. useDefaultIndentSize(props.adminPreferredIndentSize);
  188. useIsIndentSizeForced(props.isIndentSizeForced);
  189. useDisableLinkSharing(props.disableLinkSharing);
  190. useRendererConfig(props.rendererConfig);
  191. useIsEnabledMarp(props.rendererConfig.isEnabledMarp);
  192. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  193. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  194. useIsAllReplyShown(props.isAllReplyShown);
  195. useIsUploadAllFileAllowed(props.isUploadAllFileAllowed);
  196. useIsUploadEnabled(props.isUploadEnabled);
  197. const { pageWithMeta } = props;
  198. const pageId = pageWithMeta?.data._id;
  199. const revisionBody = pageWithMeta?.data.revision?.body;
  200. useCurrentPathname(props.currentPathname);
  201. const { data: currentPage } = useSWRxCurrentPage(pageWithMeta?.data ?? null); // store initial data
  202. const { trigger: mutateCurrentPage } = useSWRMUTxCurrentPage();
  203. const { trigger: mutateCurrentPageYjsDataFromApi } = useSWRMUTxCurrentPageYjsData();
  204. const { mutate: mutateEditingMarkdown } = useEditingMarkdown();
  205. const { data: currentPageId, mutate: mutateCurrentPageId } = useCurrentPageId();
  206. const { mutate: mutateIsNotFound } = useIsNotFound();
  207. const { mutate: mutateIsLatestRevision } = useIsLatestRevision();
  208. const { mutate: mutateRemoteRevisionId } = useRemoteRevisionId();
  209. const { mutate: mutateTemplateTagData } = useTemplateTagData();
  210. const { mutate: mutateTemplateBodyData } = useTemplateBodyData();
  211. const { mutate: mutateCurrentPageYjsData } = useCurrentPageYjsData();
  212. useSetupGlobalSocket();
  213. useSetupGlobalSocketForPage(pageId);
  214. // Store initial data (When revisionBody is not SSR)
  215. useEffect(() => {
  216. if (!props.skipSSR) {
  217. return;
  218. }
  219. if (currentPageId != null && !props.isNotFound) {
  220. const mutatePageData = async() => {
  221. const pageData = await mutateCurrentPage();
  222. mutateEditingMarkdown(pageData?.revision?.body);
  223. mutateCurrentPageYjsDataFromApi();
  224. };
  225. // If skipSSR is true, use the API to retrieve page data.
  226. // Because pageWIthMeta does not contain revision.body
  227. mutatePageData();
  228. }
  229. }, [currentPageId, mutateCurrentPage, mutateCurrentPageYjsDataFromApi, mutateEditingMarkdown, props.isNotFound, props.skipSSR]);
  230. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  231. useEffect(() => {
  232. const decodedURI = decodeURI(window.location.pathname);
  233. if (isClient() && decodedURI !== props.currentPathname) {
  234. const { search, hash } = window.location;
  235. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  236. }
  237. }, [props.currentPathname, router]);
  238. // initialize mutateEditingMarkdown only once per page
  239. // need to include useCurrentPathname not useCurrentPagePath
  240. useEffect(() => {
  241. if (props.currentPathname != null) {
  242. mutateEditingMarkdown(revisionBody);
  243. }
  244. }, [mutateEditingMarkdown, revisionBody, props.currentPathname]);
  245. useEffect(() => {
  246. mutateRemoteRevisionId(pageWithMeta?.data.revision?._id);
  247. }, [mutateRemoteRevisionId, pageWithMeta?.data.revision?._id]);
  248. useEffect(() => {
  249. mutateCurrentPageId(pageId ?? null);
  250. }, [mutateCurrentPageId, pageId]);
  251. useEffect(() => {
  252. mutateIsNotFound(props.isNotFound);
  253. }, [mutateIsNotFound, props.isNotFound]);
  254. useEffect(() => {
  255. mutateIsLatestRevision(props.isLatestRevision);
  256. }, [mutateIsLatestRevision, props.isLatestRevision]);
  257. useEffect(() => {
  258. mutateTemplateTagData(props.templateTagData);
  259. }, [props.templateTagData, mutateTemplateTagData]);
  260. useEffect(() => {
  261. mutateTemplateBodyData(props.templateBodyData);
  262. }, [props.templateBodyData, mutateTemplateBodyData]);
  263. useEffect(() => {
  264. mutateCurrentPageYjsData(props.yjsData);
  265. }, [mutateCurrentPageYjsData, props.yjsData]);
  266. // If the data on the page changes without router.push, pageWithMeta remains old because getServerSideProps() is not executed
  267. // So preferentially take page data from useSWRxCurrentPage
  268. const pagePath = currentPage?.path ?? pageWithMeta?.data.path ?? props.currentPathname;
  269. const title = generateCustomTitleForPage(props, pagePath);
  270. return (
  271. <>
  272. <Head>
  273. <title>{title}</title>
  274. </Head>
  275. <div className="dynamic-layout-root justify-content-between">
  276. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  277. <PageView
  278. className="d-edit-none"
  279. pagePath={pagePath}
  280. initialPage={pageWithMeta?.data}
  281. rendererConfig={props.rendererConfig}
  282. />
  283. <EditablePageEffects />
  284. <DisplaySwitcher />
  285. <PageStatusAlert />
  286. </div>
  287. </>
  288. );
  289. };
  290. const BasicLayoutWithEditor = ({ children }: { children?: ReactNode }): JSX.Element => {
  291. const editorModeClassName = useEditorModeClassName();
  292. return <BasicLayout className={editorModeClassName}>{children}</BasicLayout>;
  293. };
  294. type LayoutProps = Props & {
  295. children?: ReactNode
  296. }
  297. const Layout = ({ children, ...props }: LayoutProps): JSX.Element => {
  298. // init sidebar config with UserUISettings and sidebarConfig
  299. useInitSidebarConfig(props.sidebarConfig, props.userUISettings);
  300. return <BasicLayoutWithEditor>{children}</BasicLayoutWithEditor>;
  301. };
  302. Page.getLayout = function getLayout(page: React.ReactElement<Props>) {
  303. return (
  304. <>
  305. <GrowiPluginsActivator />
  306. <DrawioViewerScript drawioUri={page.props.rendererConfig.drawioUri} />
  307. <Layout {...page.props}>
  308. {page}
  309. </Layout>
  310. <UnsavedAlertDialog />
  311. <DescendantsPageListModal />
  312. <DrawioModal />
  313. <HandsontableModal />
  314. <QuestionnaireModalManager />
  315. <TemplateModal />
  316. <LinkEditModal />
  317. <TagEditModal />
  318. <ConflictDiffModal />
  319. </>
  320. );
  321. };
  322. function getPageIdFromPathname(currentPathname: string): string | null {
  323. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  324. }
  325. class MultiplePagesHitsError extends ExtensibleCustomError {
  326. pagePath: string;
  327. constructor(pagePath: string) {
  328. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  329. this.pagePath = pagePath;
  330. }
  331. }
  332. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  333. const { model: mongooseModel } = await import('mongoose');
  334. const req: CrowiRequest = context.req as CrowiRequest;
  335. const { crowi } = req;
  336. const { revisionId } = req.query;
  337. const Page = crowi.model('Page') as PageModel;
  338. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  339. const { pageService, configManager } = crowi;
  340. let currentPathname = props.currentPathname;
  341. const pageId = getPageIdFromPathname(currentPathname);
  342. const isPermalink = _isPermalink(currentPathname);
  343. const { user } = req;
  344. if (!isPermalink) {
  345. // check redirects
  346. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  347. if (chains != null) {
  348. // overwrite currentPathname
  349. currentPathname = chains.end.toPath;
  350. props.currentPathname = currentPathname;
  351. // set redirectFrom
  352. props.redirectFrom = chains.start.fromPath;
  353. }
  354. // check whether the specified page path hits to multiple pages
  355. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  356. if (count > 1) {
  357. throw new MultiplePagesHitsError(currentPathname);
  358. }
  359. }
  360. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  361. const page = pageWithMeta?.data as unknown as PageDocument;
  362. // add user to seen users
  363. if (page != null && user != null) {
  364. await page.seen(user);
  365. }
  366. // populate & check if the revision is latest
  367. if (page != null) {
  368. page.initLatestRevisionField(revisionId);
  369. props.isLatestRevision = page.isLatestRevision();
  370. const ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  371. props.skipSSR = await skipSSR(page, ssrMaxRevisionBodyLength);
  372. await page.populateDataToShowRevision(props.skipSSR); // shouldExcludeBody = skipSSR
  373. }
  374. props.pageWithMeta = pageWithMeta;
  375. }
  376. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  377. const req: CrowiRequest = context.req as CrowiRequest;
  378. const { crowi } = req;
  379. const Page = crowi.model('Page') as PageModel;
  380. const { currentPathname } = props;
  381. const pageId = getPageIdFromPathname(currentPathname);
  382. const isPermalink = _isPermalink(currentPathname);
  383. const page = props.pageWithMeta?.data;
  384. if (props.isIdenticalPathPage) {
  385. props.isNotCreatable = true;
  386. }
  387. else if (page == null) {
  388. props.isNotFound = true;
  389. props.isNotCreatable = !isCreatablePage(currentPathname);
  390. // check the page is forbidden or just does not exist.
  391. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  392. props.isForbidden = count > 0;
  393. }
  394. else {
  395. props.isNotFound = page.isEmpty;
  396. props.isNotCreatable = false;
  397. props.isForbidden = false;
  398. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  399. if (isPermalink && page.isEmpty) {
  400. props.currentPathname = page.path;
  401. }
  402. // /path/to/page ==> /62a88db47fed8b2d94f30000
  403. if (!isPermalink && !page.isEmpty) {
  404. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  405. if (!isToppage) {
  406. props.currentPathname = `/${page._id}`;
  407. }
  408. }
  409. if (!props.skipSSR) {
  410. props.yjsData = await crowi.pageService.getYjsData(page._id.toString());
  411. }
  412. }
  413. }
  414. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  415. // const req: CrowiRequest = context.req as CrowiRequest;
  416. // const { crowi } = req;
  417. // const UserModel = crowi.model('User');
  418. // if (isUserPage(props.currentPagePath)) {
  419. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  420. // if (user != null) {
  421. // props.pageUser = JSON.stringify(user.toObject());
  422. // }
  423. // }
  424. // }
  425. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  426. const req: CrowiRequest = context.req as CrowiRequest;
  427. const { crowi } = req;
  428. const {
  429. searchService, configManager, aclService,
  430. } = crowi;
  431. props.isSearchServiceConfigured = searchService.isConfigured;
  432. props.isSearchServiceReachable = searchService.isReachable;
  433. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  434. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  435. // props.isMailerSetup = mailService.isMailerSetup;
  436. props.isAclEnabled = aclService.isAclEnabled();
  437. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  438. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  439. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  440. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  441. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  442. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  443. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  444. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  445. props.isUploadAllFileAllowed = crowi.fileUploadService.getFileUploadEnabled();
  446. props.isUploadEnabled = crowi.fileUploadService.getIsUploadable();
  447. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  448. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  449. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  450. props.sidebarConfig = {
  451. isSidebarCollapsedMode: configManager.getConfig('crowi', 'customize:isSidebarCollapsedMode'),
  452. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  453. };
  454. props.rendererConfig = {
  455. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  456. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  457. isEnabledMarp: configManager.getConfig('crowi', 'customize:isEnabledMarp'),
  458. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  459. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  460. drawioUri: configManager.getConfig('crowi', 'app:drawioUri'),
  461. plantumlUri: configManager.getConfig('crowi', 'app:plantumlUri'),
  462. // XSS Options
  463. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  464. sanitizeType: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  465. customAttrWhitelist: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  466. customTagWhitelist: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  467. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  468. };
  469. props.ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  470. }
  471. /**
  472. * for Server Side Translations
  473. * @param context
  474. * @param props
  475. * @param namespacesRequired
  476. */
  477. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  478. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  479. props._nextI18Next = nextI18NextConfig._nextI18Next;
  480. }
  481. const getAction = (props: Props): SupportedActionType => {
  482. if (props.isNotCreatable) {
  483. return SupportedAction.ACTION_PAGE_NOT_CREATABLE;
  484. }
  485. if (props.isForbidden) {
  486. return SupportedAction.ACTION_PAGE_FORBIDDEN;
  487. }
  488. if (props.isNotFound) {
  489. return SupportedAction.ACTION_PAGE_NOT_FOUND;
  490. }
  491. if (pagePathUtils.isUsersHomepage(props.pageWithMeta?.data.path ?? '')) {
  492. return SupportedAction.ACTION_PAGE_USER_HOME_VIEW;
  493. }
  494. return SupportedAction.ACTION_PAGE_VIEW;
  495. };
  496. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  497. const req = context.req as CrowiRequest;
  498. const { user } = req;
  499. const result = await getServerSideCommonProps(context);
  500. // check for presence
  501. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  502. if (!('props' in result)) {
  503. throw new Error('invalid getSSP result');
  504. }
  505. const props: Props = result.props as Props;
  506. if (props.redirectDestination != null) {
  507. return {
  508. redirect: {
  509. permanent: false,
  510. destination: props.redirectDestination,
  511. },
  512. };
  513. }
  514. if (user != null) {
  515. props.currentUser = user.toObject();
  516. }
  517. try {
  518. await injectPageData(context, props);
  519. }
  520. catch (err) {
  521. if (err instanceof MultiplePagesHitsError) {
  522. props.isIdenticalPathPage = true;
  523. }
  524. else {
  525. throw err;
  526. }
  527. }
  528. await injectRoutingInformation(context, props);
  529. injectServerConfigurations(context, props);
  530. await injectNextI18NextConfigurations(context, props, ['translation']);
  531. addActivity(context, getAction(props));
  532. return {
  533. props,
  534. };
  535. };
  536. export default Page;